<template>
<div class="documentprocess">
  <div>
    <el-breadcrumb @click="specialInitialProcess" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/initiatingprocess' }" v-if="isShowItem">{{process[processNumber]}}</el-breadcrumb-item>
      <span @click.stop=";" v-if="isShowSpan">{{process[processNumber]}}<i class="el-icon-arrow-right"></i> </span>
      <span @click.stop=";">5-8单证流程</span>
    </el-breadcrumb>
  </div>

  <el-tabs v-model="tabValue" type="card" @tab-click="documentProcessChoose">
    <el-tab-pane label="工厂发货" name="1">
      <factoryDeliveryVue ref="fd" :tabOne="roles.documentprocess_fd_notice == 'W' ? true : false" :tabTwo="roles.documentprocess_fd_confirm == 'W' ? true : false" :bus="flow5Bus" :fromDTab="fromDTab"  :data="saveData.documentprocess_fd"></factoryDeliveryVue>
    </el-tab-pane>
    <el-tab-pane label="单证员报关" name="2"  v-if="(processNumber == 0 || processNumber == 3) ? true : roles.documentprocess_cc !='H'">
      <documentMemberDeclaringCustomsVue   :bus="flow5Bus" :relatedData="saveData.documentprocess_fd.documentprocess_fd_notice" :editable="roles.documentprocess_cc == 'W' ? true : false " :relation="relation" :data="saveData.documentprocess_cc"></documentMemberDeclaringCustomsVue>
    </el-tab-pane>
    <el-tab-pane  label="向工厂索要发票" name="3" v-if=" (processNumber == 0 || processNumber == 3) ? true : roles.documentprocess_askInvoice !='H'">
      <ask-for-invoice :bus="flow5Bus"  :editable="roles.documentprocess_askInvoice == 'W' ? true : false" :relation="relation" :relatedData="saveData.documentprocess_cc" :data="saveData.documentprocess_askInvoice" />
    </el-tab-pane>
    <el-tab-pane   label="核销资料收集" name="4" v-if="(processNumber == 0 || processNumber == 3) ? true : roles.documentprocess_collectionData !='H'">
      <collection-data    :editable="roles.documentprocess_collectionData == 'W' ? true : false" :data="saveData.documentprocess_collectionData" />
    </el-tab-pane>
  </el-tabs>

  <div class="documentprocess-fixed">
    <fixed-form v-if="hasBind" ref="fixedForm" :saveAndSend="saveAndSend" :saveData="saveData" :editable="editable" :sendMenus="sendMenus" processName="documentprocess" />
    <fixed-form v-else ref="fixedForm" :saveAndSend="false" :saveData="saveData" :editable="false" :sendMenus="sendMenus" processName="documentprocess" />
  </div>
</div>
</template>

<script>
import Vue from 'vue'
import factoryDeliveryVue from './factoryDelivery/factoryDeliveryVue.vue'
import documentMemberDeclaringCustomsVue from './documentMemberDeclaringCustoms/documentMemberDeclaringCustomsVue.vue'
import askForInvoice from './askForInvoiceToTheFactory/askForInvoiceToTheFactory.vue'
import collectionData from './collectionData/collectionData.vue'

import fixedForm from '../common/fixedForm.vue';

import {
  uploadFiles,
  getSendMenus,
  getData,
  getPermission
} from '@/server/initiatingprocess';
import {
  getStore
} from '@/assets/js/common'

export default {
  created() {
    this.saveData = _.cloneDeep(this.$store.state.documentprocess);

    this.roles = {
          documentprocess_askInvoice: "R",
          documentprocess_cc: "R",
          documentprocess_cc_customsDeclarationBox: "R",
          documentprocess_cc_customsDeclarationContract: "R",
          documentprocess_cc_customsDeclarationInvoice: "R",
          documentprocess_cc_declarationElements: "R",
          documentprocess_cc_declarationForm: "R",
          documentprocess_cc_letterOfDelivery: "R",
          documentprocess_collectionData: "R",
          documentprocess_fd: "W",
          documentprocess_fd_confirm: "R",
          documentprocess_fd_notice: "W",
    };
    this.sendMenus = [];

    this.flow5Bus = new Vue();

    let _this = this;
    this.flow5Bus.$on('bind-new-ftc', function(){
      _this.hasBind = true;
      _this.$forceUpdate();
    });



    
  },
  mounted() {
    //刷新浏览器时，避免重叠
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';





    getSendMenus({
      'flowId': 5
    }).then((response) => {
      this.sendMenus = response.data.datas[0];
      this.$forceUpdate();
    });

    //判断面包屑二级路由是否可退回
    let isCreatFlow = getStore('isCreatFlow');
    this.isShowItem = !isCreatFlow ? false : true;
    this.isShowSpan = !isCreatFlow ? true : false;
  },
  beforeRouteEnter(to, from, next) {

    let dom = document.querySelector('.initiatingprocess  .routers-ctrl');
    if (dom) {
      dom.style.zIndex = '-1';
    }

    next(vm => {

      if (to.query.tab) {

        vm.tabValue = to.query.tab;

        vm.$message({
          message: '请先绑定订单，否则无法保存和发送',
          type: 'warning',
          duration: 3000,
          showClose: true
        });

        if (to.query.tab == 1) {
          let temp = vm.$children[1];
          // temp.$children[1].$children[0]工厂发货

          let cdi = temp.$children[1].$children[0];
          cdi.tabValue = to.query.subTab;

        }

        if (to.query.tab == 2) {
          let temp = vm.$children[1];
          // temp.$children[2].$children[0] 单证员报关
          let cdi = temp.$children[2].$children[0];
          cdi.tabValue = to.query.subTab;

          //直接通过路由点进去时，将 clickTimes次数设置为 2
          cdi.$children[0].$children[to.query.subTab].$children[0].clickTimes = 2;
        }


               /**
     * 获取显示tab的权限
     */

    let tabsPer = [
      {
        id: "#tab-1",
        show: true,
      }, {
        id: "#tab-2",
        show: true
      }, {
        id: "#tab-3",
        show: true
      }, {
        id: "#tab-4",
        show: true
      }
    ];

      let tabs = ["documentprocess_fd", "documentprocess_cc", "documentprocess_askInvoice", "documentprocess_collectionData"]

      getPermission({flowId: 5, currNodeId: ''}).then((response) => {

        let tabsPerData = response.data.datas[0];

        tabs.forEach((tabname,index) => {
          let temp = tabsPerData.find(e => e.itemName == tabname)
          if (temp.permission == 'H'){
            tabsPer[index].show = false;
          } else {
            tabsPer[index].show = true;
          }
        });

        //
        tabsPer.forEach(e => {
          if (e.show) {
            document.querySelector(e.id).style.display =  'inline-block';
          } else {
          document.querySelector(e.id).style.display =  'none';
          }
        })
      });

      }


      //从其他位置跳转过来
      if (to.query.dTab) {

        vm.processNumber = parseInt(to.query.itemStatus);

        vm.hasBind = true;
        vm.fromDTab = true;

        vm.tabValue = '' + to.query.dTab;

        if (to.query.dTab == 1) {
          let temp = vm.$children[1];
          let cdi = temp.$children[1].$children[0];
          cdi.tabValue = '1';
        }

        if (to.query.tab == 2) {
          let temp = vm.$children[1];
          let cdi = temp.$children[2].$children[0];
          cdi.tabValue = '1';

          //直接通过路由点进去时，将 clickTimes次数设置为 2
          cdi.$children[0].$children[to.query.subTab].$children[0].clickTimes = 2;
        }

        vm.relation = false;

        let params = {
          flowId: to.query.flowId,
          currNodeId: to.query.currNodeId
        };


        if (to.query.isHive == 1) {

          vm.$store.commit('documentprocess/SET_SAVE');
          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName,
            isHive: 1
          }).then((response) => {

            let data = response.data.datas[0];


            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }

              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              // if ((k == 'documentprocess_cc_df_prodAndDesc') || (k == 'documentprocess_cc_df_quaAndWeight')){
              //   if (_.isString(v)){
              //     return v.split(',');
              //   } else {
              //     return [];
              //   }
              // }

              if ((k == 'documentprocess_cc_df_quantityAndUnit') || (k == 'documentprocess_cc_df_weightAndUnit')){
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }


              return v;
            });


            _.extend(vm.saveData, data);

            let approvalIndex, approvalFullName, names = [];

            if (data.role) {
              vm.editable = data.role.DEFAULT == 'W' ? true : false;

              for (var prop in vm.roles) {
                vm.roles[prop] = data.role.DEFAULT ;
              }

              vm.saveAndSend = vm.editable;

              let copyApprovals = _.cloneDeep(data.approvals);


              for (let i = 0; i < copyApprovals.length ; i++) {
                for (var prop in vm.saveData.originApprovals[i]) {
                  if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                    vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                  }
                }
              }

              vm.saveData.isSalesMan = false;
            } else {
              vm.saveData.isSalesMan = true;
            }

            getSendMenus(params).then((response) => {
              vm.sendMenus = response.data.datas[0];

              vm.$forceUpdate();
              vm.$refs.fixedForm.isForceUpdate = true;
              vm.$refs.fixedForm.$forceUpdate();
            });

          });
        } else {

          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName
          }).then((response) => {

            let data = response.data.datas[0];


            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }
              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              // if ((k == 'documentprocess_cc_df_prodAndDesc') || (k == 'documentprocess_cc_df_quaAndWeight')){
              //   if (_.isString(v)){
              //     return v.split(',');
              //   } else {
              //     return [];
              //   }
              // }

              if ((k == 'documentprocess_cc_df_quantityAndUnit') || (k == 'documentprocess_cc_df_weightAndUnit')){
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });


            _.extend(vm.saveData, data);

            let approvalIndex, approvalFullName, names = [];

            if (data.role) {
              data.role.forEach((e) => {
                if (e.itemName.indexOf("item") === -1) {
                  vm.roles[e.itemName] = e.permission;
                } else {
                  let num = Number(e.itemName[e.itemName.length - 1]) - 1;
                  if (e.permission == 'W') {
                    approvalIndex = num;
                    approvalFullName = e.itemName;
                  }
                }
              });

              if (vm.roles.documentprocess_cc_letterOfDelivery == 'W'){
                vm.roles.documentprocess_cc = 'W';
                vm.relation = true;
              }

              vm.editable = true;
              vm.saveAndSend = true;

              let copyApprovals = _.cloneDeep(data.approvals);


              if (approvalIndex !== undefined) {
                if (approvalIndex >= 0) {
                  for (let i = 0; i <= approvalIndex; i++) {
                    if (copyApprovals[i]){
                      for (var prop in vm.saveData.originApprovals[i]) {
                        if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                          vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                        }
                      }
                      vm.saveData.originApprovals[i].approval_id = '' + copyApprovals[i].id;
                    }
                  }
                }

                let date = new Date();
                vm.saveData.originApprovals[approvalIndex].rw = 'W';
                vm.saveData.originApprovals[approvalIndex].approval_time = date.toLocaleDateString() + ' ' + date.toTimeString().slice(0, 9);
                vm.saveData.originApprovals[approvalIndex].approval_username = JSON.parse(getStore('userMsg')).userName;;

              } else if (copyApprovals.length > 0){
                for (let i = 0; i < copyApprovals.length; i++) {

                  for (var prop in vm.saveData.originApprovals[i]) {
                    if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                      vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                    }
                  }
                  vm.saveData.originApprovals[i].approval_id = '' + copyApprovals[i].id;
                }
              }


              vm.saveData.isSalesMan = false;
            } else {
              vm.saveData.isSalesMan = true;
            }

            getSendMenus(params).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.$forceUpdate();
              vm.$refs.fixedForm.isForceUpdate = true;
              vm.$refs.fixedForm.$forceUpdate();
            });

          });
        }
      }
    });
  },
  beforeRouteLeave(to, from, next){
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';
    if (!this.$store.state.documentprocess.hasSaved){
      this.$confirm('您填写的内容尚未保存或发送,是否要离开?', '提示', {
        confirmButtonText: '离开',
        cancelButtonText: '留下',
        type: 'warning'
      }).then(() => {
        next();
      }).catch(() => {
        Array.prototype.forEach.call(document.getElementsByTagName('*'), (e) => {
          e.blur();
        });
        next(false);
      });
    } else {
      next();
    }
  },
  data() {
    return {
      isShowItem: false,
      isShowSpan: false,
      tabValue: '1',
      editable: true,
      relation: true,
      process: ['待发事项', '待办事项', '已办事项','发起流程'],
      processNumber: 3,
      hasBind: false,
      fromDTab: false,
      saveAndSend: true,
    }
  },

  props: {},
  components: {
    factoryDeliveryVue,
    documentMemberDeclaringCustomsVue,
    askForInvoice,
    collectionData,
    fixedForm
  },
  methods: {
    documentProcessChoose(tab) {
      //切换选项卡切换流程

      if (tab.$children[0].clickTimes == 0) {
        tab.$children[0].clickTimes++;
        tab.$children[0].$forceUpdate();
      }

    },
    specialInitialProcess() {
      let cls = event.target.classList;
      if (cls.contains("el-icon-arrow-right") && cls.contains("el-breadcrumb__separator")) return;
      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    }
  }
}
</script>


<style  lang="scss">
.documentprocess {

    padding: 20px;

    i.el-breadcrumb__separator {
        margin: 0 !important;
    }

    i.el-breadcrumb__separator[class*=icon] {
        margin: 0 !important;
        padding: 0 9px !important;
    }

    .operation-icon {
        position: absolute;
        right: 3px;
        top: 50%;
        transform: translate(0, -50%);
    }

    .documentprocess-fixed {
        border: 1px solid #999;
        margin-top: 20px;
    }
}
</style>
